package top.liumiao.chatwx.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.XmlUtil;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
import top.liumiao.chatwx.entity.Message;
import top.liumiao.chatwx.utils.BigModelNew;
import top.liumiao.chatwx.utils.TokenCheckUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Logger
@RestController
@RequestMapping("/wx")
public class TokenCheckController {


    @Value("${wechat.mp.token}")
    private String token;
    @Value("${ai.xunfei.hostUrl}")
    private String hostUrl;
    @Value("${ai.xunfei.domain}")
    private String domain;
    @Value("${ai.xunfei.appid}")
    private String appid;
    @Value("${ai.xunfei.apiSecret}")
    private String apiSecret;
    @Value("${ai.xunfei.apiKey}")
    private String apiKey;

    @GetMapping("/")
    public String index(HttpServletResponse response, HttpServletRequest request) throws Exception {
        return TokenCheckUtil.checkToken(request, token);
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void index(@RequestBody String xml, HttpServletResponse resp) throws IOException {
        // 将接收到的xml消息转为map
        Map<String, Object> stringObjectMap = XmlUtil.xmlToMap(xml);

        // 将map转为标准的message对象
        top.liumiao.chatwx.entity.Message message = BeanUtil.fillBeanWithMap(stringObjectMap, new Message(), false);
        log.info("接收到来自" + message.getFromUserName() + "的消息，内容是" + message.getContent());

        // 创建新的 BigModelNew 实例
        BigModelNew bigModelNew = new BigModelNew(hostUrl, domain, appid, apiSecret, apiKey, IdUtil.randomUUID());

        // 设置响应头
        resp.setContentType("text/xml;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 获取输出流
        PrintWriter writer = resp.getWriter();

        try {
            // 构建初始的XML头部
            writer.write("<xml>");
            writer.write("<ToUserName><![CDATA[" + message.getFromUserName() + "]]></ToUserName>");
            writer.write("<FromUserName><![CDATA[" + message.getToUserName() + "]]></FromUserName>");
            writer.write("<CreateTime>" + System.currentTimeMillis() + "</CreateTime>");
            writer.write("<MsgType><![CDATA[text]]></MsgType>");
            log.debug("写入初始的XML头部");

            // 开始流式写入内容
            writer.write("<Content><![CDATA[");
            log.debug("开始流式写入内容");

            bigModelNew.askStream(message.getContent(), contentChunk -> {
                // 逐步写入内容片段
                log.debug("接收到内容片段: {}", contentChunk);
                writer.write(contentChunk);
                writer.flush(); // 确保内容立即发送到客户端
            });
            writer.write("]]></Content>");
            log.debug("结束内容片段写入");

            // 结束XML
            writer.write("</xml>");
            log.debug("结束XML写入");
        } catch (Exception e) {
            log.error("Error processing request", e);
            // 如果发生异常，返回错误信息
            writer.write("<xml><Content><![CDATA[系统异常，请稍后重试]]></Content></xml>");
            log.debug("返回错误信息");
        } finally {
            writer.close();
            log.debug("关闭 PrintWriter 输出流");
        }
    }



/*
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void index(@RequestBody String xml, HttpServletResponse resp) throws IOException {
        // 将接收到的xml消息转为map
        Map<String, Object> stringObjectMap = XmlUtil.xmlToMap(xml);

        // 将map转为标准的message对象
        top.liumiao.chatwx.entity.Message message = BeanUtil.fillBeanWithMap(stringObjectMap, new Message(), false);
        log.info("接收到微信发来的消息：{}", message);
        log.info("接收到来自" + message.getFromUserName() + "的消息，内容是" + message.getContent());

        // 创建新的 BigModelNew 实例
        BigModelNew bigModelNew = new BigModelNew(hostUrl, domain, appid, apiSecret, apiKey, IdUtil.randomUUID());

        // 调用 bigModelNew.ask(message.getContent()) 并等待返回的结果
        try {
            // 构建返回的map
            Map<Object, Object> resMap = new HashMap<>();
            resMap.put("ToUserName", message.getFromUserName());
            resMap.put("FromUserName", message.getToUserName());
            resMap.put("CreateTime", System.currentTimeMillis());
            resMap.put("MsgType", "text");
            resMap.put("Content", bigModelNew.ask(message.getContent()));  // 使用 bigModelNew.ask() 返回的结果作为回复内容

            // 返回处理后的XML
            resp.setContentType("text/xml;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write(XmlUtil.mapToXmlStr(resMap, "xml"));
        } catch (Exception e) {
            log.error("Error processing request", e);
        }

    }*/


/*    @RequestMapping(value="/",method= RequestMethod.POST)
    public void index(@RequestBody String xml,HttpServletResponse resp) throws IOException  {
        //将接收到的xml消息转为map
        Map<String, Object> stringObjectMap = XmlUtil.xmlToMap(xml);
        //将map转为标准的message对象
        top.liumiao.chatwx.entity.Message message = BeanUtil.fillBeanWithMap(stringObjectMap, new Message(), false);
        log.info("接收到微信发来的消息：{}",message);
        log.info("接收到来自"+message.getFromUserName()+"的消息，内容是"+message.getContent());

        //返回的内容
        String resStr = "收到您发送的{"+message.getContent()+"}消息";

        //构建返回的map
        Map<Object, Object> resMap = new HashMap<>();
        resMap.put("ToUserName",message.getFromUserName());
        resMap.put("FromUserName",message.getToUserName());
        resMap.put("CreateTime",System.currentTimeMillis());
        resMap.put("MsgType","text");
        resMap.put("Content",resStr);

        resp.setContentType("text/xml;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(XmlUtil.mapToXmlStr(resMap,"xml"));

    }*/

}

